﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.Models.JoinParty;

namespace ZHDJ.JoinParty.BLL
{
    public class ModuleUtil
    {
        #region 网站管理员
        /// <summary>
        /// 是否网站管理员
        /// </summary>
        /// <param name="loginID"></param>
        /// <returns></returns>
        public static bool IsAdmin(string loginID)
        {
            bool flag = false;
            foreach (string item in ModuleConfigs.SystemAdministrators)
            {
                if (loginID.Equals(item))
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }
        #endregion

        #region 获取用户信息
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="LoginID"></param>
        /// <returns></returns>
        public static DataSet GetUsetMassage(string LoginID)
        {
            StringBuilder sbSql = new StringBuilder();
            sbSql.AppendFormat(@"select LoginID,UserName,case Gender when 0 then '男' when 1 then '女' end as GenderEx,IdentityCard,MobileNo,Address,ImageUrl from tblpartyorgmember
                                where LoginID='{0}'", LoginID);
            DataSet ds = MySqlHelper.ExecuteDataSet(sbSql.ToString());
            return ds;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="LoginID"></param>
        /// <returns></returns>
        public static DataSet GetUsetMassageByAppllicationID(string AppllicationID)
        {
            StringBuilder sbSql = new StringBuilder();
            sbSql.AppendFormat(@"select om.UserName,om.Address,om.WorkUnit,om.UnitJob from tblPartyJoinApplycation ja
                                left join tblPartyOrgMember om on ja.LoginID=om.LoginID
                                where ja.AppllicationID='{0}'", AppllicationID);
            DataSet ds = MySqlHelper.ExecuteDataSet(sbSql.ToString());
            return ds;
        }
        #endregion

        /// <summary>
        /// 返回工作指引
        /// </summary>
        /// <param name="CurrentStepID"></param>
        /// <returns></returns>
        public static string GetWorkPointConent(string CurrentStepID)
        {
            var ps = ZHDJ.WebPage.RolePageBase.DB.PartyJoinProcesss.Find(CurrentStepID);

            return ps.WorkPoint;

        }

        #region 根据组织ID和步骤ID获取待处理流程ID
        /// <summary>
        /// 根据当前用户判断登陆ID是否重复
        /// </summary>
        /// <param name="loginID"></param>
        /// <param name="CurrentLoginID"></param>
        /// <returns></returns>
        public static bool CheckLoginIDCount(string loginID, string CurrentLoginID)
        {

            string sql = string.Format(@"select count(LoginID) from  tblpartyorgmember
                                where (LoginID='{0}'  or MobileNo='{0}' or IdentityCard='{0}') and LoginID!='{1}' ", loginID, CurrentLoginID);
            return MySqlHelper.ExecuteNonQuery(sql) > 0;
        }
        #endregion
        #region 根据组织ID和步骤ID获取待处理流程ID
        /// <summary>
        /// 根据组织ID和步骤ID获取待处理流程ID
        /// </summary>
        /// <param name="BranchID"></param>
        /// <param name="CurrentStepID"></param>
        /// <returns></returns>
        public static DataSet BranchLoginStantID(string BranchID, string StepID, string currentStandID = "")
        {

            using (SqlCommand cmd = new SqlCommand())
            {
                StringBuilder sbsql = new StringBuilder();
                sbsql.AppendFormat(@" select LE.* from tblPartyJoinApplycation data 
                                        inner join tblPartyJoinLinkExample LE on data.AppllicationID=LE.AppllicationID
                                    where LE.CurrentStepID='{0}' and (LE.Status=0 or Le.Status is null) and data.BranchID='{1}'", StepID, BranchID);
                if (currentStandID != "")
                    sbsql.AppendFormat(" and LE.StandID='{0}'", currentStandID);
                DataSet ds = MySqlHelper.ExecuteDataSet(sbsql.ToString());
                return ds;
            }
        }
        #endregion

        /// <summary>
        /// 获取组织管理员 组织书记 key:LoginID  value:UserName
        /// </summary>
        /// <param name="branchid">组织id</param>
        /// <param name="type">空：所有，1：组织管理员 2：组织书记 </param>
        /// <returns></returns>
        public static Dictionary<string, string> GetBranchAdminToDictionaryEx(string branchid, string type)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            DataTable dt = new DataTable();
            dt = GetBranchAdmin(branchid, type).Tables[0];
            foreach (DataRow item in dt.Rows)
            {
                dic.Add(Convert.ToString(item["BranchID"]), Convert.ToString(item["BranchID"]));
            }
            return dic;
        }

        /// <summary>
        /// 获取组织管理员 组织书记
        /// </summary>
        /// <param name="branchid">组织id</param>
        /// <param name="type">空：所有，1：组织管理员 2：组织书记 </param>
        /// <returns></returns>
        public static DataSet GetBranchAdmin(string branchid, string type)
        {
            type = "";

            StringBuilder sb = new StringBuilder();
            sb.Append(@" select temp.*,a.MobileNo,a.UserName from (
                            SELECT '' LoginID,'' BranchID ");
            //所有的使用党务工作者就可以
            if (type == "" || type == "1")
            {
                sb.AppendFormat(@" union 
                            SELECT LoginID,BranchID FROM tblpartyorgbranchadmin WHERE BranchID = '{0}'
                            union 
                            SELECT LoginID,BranchID FROM tblpartyorgmember WHERE BranchID = '{0}' and IsPartyWorker = 1 ", branchid);
            }
            if (type == "" || type == "2")
            {
                sb.AppendFormat(@" union
                            SELECT LoginID,BranchID FROM tblpartyorgbranchworker WHERE BranchID = '{0}' and WorkeType='shuji' ", branchid);
            }
            sb.Append(@"  ) temp
                            left join tblpartyorgmember a on(a.LoginID=temp.LoginID)
                            where IFNULL(a.UserName,'')<>'' and IFNULL(a.LoginID,'')<>'' GROUP BY BranchID");
            return MySqlHelper.ExecuteDataSet(sb.ToString());
        }

        #region 注册用户转成普通党员账户
        /// <summary>
        /// 注册用户转成普通党员账户 更新：
        /// </summary>
        /// <param name="AppllicationID">申请ID</param>
        /// <param name="JoinPartyDate">入党时间</param>
        /// <param name="BeRegularDate">转正时间</param>
        public static void UpdateUserMassage(string AppllicationID, string runSate = "", string JoinPartyDate = "", string BeRegularDate = "")
        {
            var AppModel = ZHDJ.WebPage.RolePageBase.DB.PartyJoinApplycation.Find(AppllicationID);
            if (AppModel != null)
            {
                var oModel = ZHDJ.WebPage.RolePageBase.DB.PartyOrgMembers.Find(AppModel.LoginID);

                if (runSate != "")
                {
                    oModel.runSate = "0";
                    oModel.OrderNo = 0;
                    oModel.IsAgree = true;
                }
                if (BeRegularDate != "")
                {
                    oModel.PoliticsLineament = "01";
                    //默认入党时间加一年
                    oModel.BeRegularDate = oModel.JoinPartyDate?.AddYears(1);
                }
                if (JoinPartyDate != "")
                {
                    if (JoinPartyDate != "null")
                    {
                        //入党时间由  获取 17步支部大会讨论吸收  大会时间
                        oModel.JoinPartyDate = Convert.ToDateTime(JoinPartyDate);
                    }
                    else
                    {
                        //转为预备党员
                        oModel.PoliticsLineament = "02";

                    }
                    oModel.BeRegularDate = Convert.ToDateTime("9999-12-31");
                    oModel.pwdOverTime = Convert.ToDateTime("9999-12-31");
                }
                ZHDJ.WebPage.RolePageBase.DB.SaveChanges();
            }

        }
        /// <summary>
        /// 取消入党
        /// </summary>
        /// <param name="AppllicationID"></param>
        public static void UpdateUserMassageByCancel(string AppllicationID)
        {
            var AppModel = ZHDJ.WebPage.RolePageBase.DB.PartyJoinApplycation.Find(AppllicationID);

            if (AppModel != null)
            {
                var oModel = ZHDJ.WebPage.RolePageBase.DB.PartyOrgMembers.Find(AppModel.LoginID);

                oModel.runSate = "-1";
                oModel.OrderNo = 0;
                oModel.IsAgree = false;
                oModel.PoliticsLineament = "";
                oModel.BeRegularDate = Convert.ToDateTime("9999-12-31"); ;
                oModel.JoinPartyDate = Convert.ToDateTime("9999-12-31"); ;
                ZHDJ.WebPage.RolePageBase.DB.SaveChanges();
                //oModel.Update();
            }
        }
        #endregion

        #region 获取党工委组织ID
        /// <summary>
        /// 获取党工委组织ID
        /// </summary>
        /// <param name="branchID"></param>
        /// <returns></returns>
        public static string GetPartyAppointArray(string branchID)
        {
            List<MySql.Data.MySqlClient.MySqlParameter> parameters = new List<MySql.Data.MySqlClient.MySqlParameter>()
            {
                new MySql.Data.MySqlClient.MySqlParameter()
                {
                    DbType = DbType.String,
                    ParameterName = "BranchID",
                    Value = branchID
                }
            };
            string sql = string.Format(@" call sp_GetPartyAppointArray(?BranchID); ");
            object obj = MySqlHelper.ExecuteScalar(sql, parameters.ToArray());
            if (obj != null) return obj.ToString();
            else return "";
        }

        /// <summary>
        /// 获取上一流程上报文件ck内容
        /// </summary>
        /// <param name="AppllicationID"></param>
        /// <returns></returns>
        public static string GetUpStandCKContentByAppllicationID(string AppllicationID)
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                StringBuilder sbsql = new StringBuilder();
                sbsql.AppendFormat(@" select  Remark from tblPartyJoinLinkExample 
                                        where AppllicationID='{0}' and CurrentStepID='JoinStep37' order by CreateTime desc
                                        limit 1", AppllicationID);

                return MySqlHelper.ExecuteScalar(sbsql.ToString()).ToString();
            }
        }

        /// <summary>
        /// 获取提交ID
        /// </summary>
        /// <param name="AppllicationID"></param>
        /// <returns></returns>
        public static string GetIDByAppllicationID(string AppllicationID)
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                StringBuilder sbSql = new StringBuilder();
                sbSql.AppendFormat(@"SELECT ID from tblPartyJoinSubmit 
                                 where AppllicationID='{0}' limit 1", AppllicationID);
                return Convert.ToString(MySqlHelper.ExecuteScalar(sbSql.ToString()));
            }
        }
        #endregion


        /// <summary>
        /// 上报备案批量操作
        /// </summary>
        /// <param name="applyBranchID">申请组织ID</param>
        public static void ReportRecords(string currentBranchID, string applyBranchID, string stepID, string StandID, string currentLoginID, string currentUserName)
        {
            DataSet ds = PartyJoinChildFlow.ChildBranchLoginStantID(applyBranchID, stepID);
            string TopBranchID = GetPartyAppointArray(applyBranchID);//申请的最高级审批组织ID

            //获取todoBranchID

            ///获取子流程条数 StandID
            int ChildCount = PartyJoinChildFlow.GetChildFlowCountByStandID(StandID);
            string ParantBranchID = "";
            if (ChildCount > 0) //只有2层
            {
                //ParantBranchID = ModuleUtil.GetParentBranch(TodoBranchID);//逐层处理时，使用该代码
                ParantBranchID = ModuleUtil.GetParentBranch(TopBranchID);//当前为2层，使用该代码
            }
            //最后一步
            //if (ModuleUtil.IsAppointAdmin(SXT.Utility.SSOClient.CurrentUser.LoginID, ""))//判断当前用户是否最顶层审核用户
            //天河区委组织ID  当前步骤是党委审核
            if (ParantBranchID == "D658070EC3BF425BA8417745FDCBFCB0")
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    //主流程处理

                    //PartyJoinLinkExample oModel = new PartyJoinLinkExample() { StandID = dr["StandID"].ToString() };
                    //oModel.Load();
                    var oModel = ZHDJ.WebPage.RolePageBase.DB.PartyJoinLinkExamples.Find(dr["StandID"].ToString());
                    oModel.HandleUserID = currentLoginID;
                    oModel.HandleUserName = currentUserName;
                    oModel.HandleTime = DateTime.Now;
                    oModel.Status = (int)Enum_FlowStanceStatus.通过;

                    string Message = "";///接收处理流程反馈的消息主要判断当前步骤是否已审核过
                    ProcesUtil.ApprovalProcesStep(oModel, out Message);

                    //子流程处理
                    //PartyJoinChildFlow cfomodel = new PartyJoinChildFlow();
                    //cfomodel.ChildFlowID = dr["ChildFlowID"].ToString();
                    //cfomodel.Load();
                    var cfomodel = ZHDJ.WebPage.RolePageBase.DB.PartyJoinChildFlows.Find(PartyJoinChildFlow.GetChildFlowID(dr["StandID"].ToString()));
                    cfomodel.HandleUserID = currentLoginID;
                    cfomodel.HandleUserName = currentUserName;
                    cfomodel.HandleTime = DateTime.Now;
                    cfomodel.ToDoBranchID = ParantBranchID;
                    cfomodel.Status = (int)Enum_FlowStanceStatus.通过;
                    ZHDJ.WebPage.RolePageBase.DB.SaveChanges();
                    //cfomodel.Update();

                    //删除代办 子流程ID
                    //SXT.Party.Utility.PartyTask.TaskDone(cfomodel.StandID, SXT.Utility.SSOClient.CurrentUser.LoginID);
                }
            }
            else
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    //修改  ParantBranchID     当前子实例ToDoBranchID的上一级组织ID
                    //string ParantBranchID = ModuleUtil.GetParentBranch(currentBranchID);//当前用户上一级组织ID
                    Dictionary<string, string> dic = ModuleUtil.GetBranchAdminToDictionaryEx(TopBranchID, "");
                    string ToDoHandleUserIDs = string.Empty;
                    string ToDoHandleUserNames = string.Empty;
                    ToDoHandleUserIDs = string.Join(",", dic.Keys.ToArray());
                    ToDoHandleUserNames = string.Join(",", dic.Values.ToArray());

                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        //处理子流程为已办
                        //PartyJoinChildFlow cfOmodel = new PartyJoinChildFlow();
                        //cfOmodel.ChildFlowID = dr["ChildFlowID"].ToString();
                        //cfOmodel.Load();
                        var cfOmodel = ZHDJ.WebPage.RolePageBase.DB.PartyJoinChildFlows.Find(PartyJoinChildFlow.GetChildFlowID(dr["StandID"].ToString()));
                        cfOmodel.HandleUserID = currentLoginID;
                        cfOmodel.HandleUserName = currentUserName;
                        cfOmodel.HandleTime = DateTime.Now;
                        cfOmodel.Status = (int)Enum_FlowStanceStatus.通过;
                        ZHDJ.WebPage.RolePageBase.DB.SaveChanges();

                        //生成下一步基本信息 
                        PartyJoinChildFlow cfOmodelEx = new PartyJoinChildFlow();
                        cfOmodelEx.ChildFlowID = StringHelper.NewID;
                        cfOmodelEx.StandID = dr["StandID"].ToString();
                        cfOmodelEx.StepID = cfOmodel.StepID;
                        cfOmodelEx.Status = (int)Enum_FlowStanceStatus.未处理;
                        cfOmodelEx.ToDoHandleUserID = ToDoHandleUserIDs;
                        cfOmodelEx.ToDoHandleUserName = ToDoHandleUserNames;
                        cfOmodelEx.ToDoBranchID = TopBranchID;
                        cfOmodelEx.ApplyBranchID = applyBranchID;
                        cfOmodelEx.OrderNo = Utility.GetSortOrderNo("tblPartyJoinChildFlow", "OrderNo", "StandID='" + cfOmodelEx.StandID + "'");
                        cfOmodelEx.CreateTime = DateTime.Now;
                        WebPage.RolePageBase.DB.PartyJoinChildFlows.Add(cfOmodelEx);
                        ZHDJ.WebPage.RolePageBase.DB.SaveChanges();

                        //更新主流程todo
                        UpdateMs(cfOmodelEx.StandID, cfOmodelEx.ToDoHandleUserID, cfOmodelEx.ToDoHandleUserName);
                        //取消当前待办  流程ID
                        //SXT.Party.Utility.PartyTask.TaskDone(cfOmodelEx.StandID, SXT.Utility.SSOClient.CurrentUser.LoginID);
                        ////发送待办
                        //AddTask(cfOmodel, TopBranchID);

                    }
                }
            }
        }

        /// <summary>
        /// 获取指定级数的父节点
        /// </summary>
        /// <param name="branchID"></param>
        /// <returns></returns>
        public static string GetParentBranch(string branchID)
        {

            string sql = string.Format(@"SELECT ParentBranchID FROM tblpartyorgbranch WHERE BranchID = '{0}'", branchID);

            Object obj = MySqlHelper.ExecuteScalar(sql);
            if (obj != null) return obj.ToString();
            else return "";

        }

        #region 更新主流程todu

        public static void UpdateMs(string StandID, string ToDoHandleUserID, string ToDoHandleUserName)
        {

            StringBuilder sbsql = new StringBuilder();
            sbsql.AppendFormat(@" update tblPartyJoinLinkExample set ToDoHandleUserID='{0}', ToDoHandleUserName='{1}' where StandID='{2}' ", ToDoHandleUserID, ToDoHandleUserName, StandID);

            MySqlHelper.ExecuteNonQuery(sbsql.ToString());

        }
        #endregion

    }
}
